package cn.edu.tjufe.llp.tin.controller.part04;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;

import cn.edu.tjufe.llp.tin.constants.TestAppConstants;
import cn.edu.tjufe.llp.tin.dto.common.Rs;
import cn.edu.tjufe.llp.tin.dto.part04.BookDto;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BookControllerTestRest {
    @Autowired
    private TestRestTemplate restTemplate;
    
    /**
     * 配合@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
     */
    @LocalServerPort
    private int port;
        
    @Test
    public void testFindAll() throws Exception {
    	
        ResponseEntity<Rs<List<BookDto>>> response = restTemplate.exchange("/part04/books", HttpMethod.GET, 
        		null,
        		new ParameterizedTypeReference<Rs<List<BookDto>>>() {});
        		
        System.out.print(response.getBody());
        assertThat(response.getBody().getCode()).isEqualTo(0);
        assertThat(response.getBody().getMessage()).isEqualTo("业务处理成功");
        assertThat(response.getBody().getData().size()).isEqualTo(1);
    }    
    
    @Test
    public void testFindAll2() throws Exception {
    	
    	HttpHeaders headers = new HttpHeaders();
    	headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(TestAppConstants.URI_SCHEME_HOST).port(port).path("/part04/books")
    	        .queryParam("name", "SpringBoot")
    	        .queryParam("author", "llp");
    	
    	HttpEntity<?> entity = new HttpEntity<>(headers);

    	ResponseEntity<Rs<List<BookDto>>> response = restTemplate.exchange(
    	        builder.toUriString(), 
    	        HttpMethod.GET, 
    	        entity, 
    	        new ParameterizedTypeReference<Rs<List<BookDto>>>() {});

    	System.out.print(response.getBody());
        assertThat(response.getBody().getCode()).isEqualTo(0);
        assertThat(response.getBody().getMessage()).isEqualTo("业务处理成功");
        assertThat(response.getBody().getData().size()).isEqualTo(2);
    }
    
}
